package cn.liuweiwei.service.impl;

import cn.liuweiwei.domain.ImgFile;
import cn.liuweiwei.mapper.FileMapper;
import cn.liuweiwei.service.FileService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;


@Service
@Transactional
public class FileServiceImpl implements FileService {

    @Autowired
    private FileMapper fileMapper;

    // 插入文件，并返回插入后的数据
    @Override
    public ImgFile insertFileWithReturn(ImgFile imgFile) {
        fileMapper.insert(imgFile);
        return fileMapper.findById(imgFile.getId());
    }

    @Override
    public PageInfo<ImgFile> findFileByPage(String page, String limit) {
        PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(limit));
        List<ImgFile> imgFiles = fileMapper.findAll();
        return new PageInfo<>(imgFiles);
    }

    @Override
    public List<ImgFile> findFilesByName(String name) {
        return fileMapper.findByFileName(name);
    }

    @Override
    public void deleteFile(String id) {
        try {
            ImgFile imgFile = fileMapper.findById(id);
            String path = ResourceUtils.getURL("classpath:").getPath() + "/static/" + imgFile.getUrl();
            new File(path).delete();
            fileMapper.delete(id);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

}
